import 'package:dio/dio.dart';
import 'package:flutter_riverpod_demo/models/dictionary.dart';
import 'package:flutter_riverpod_demo/utils/consts/server_url.dart';
import 'package:flutter_riverpod_demo/utils/http.dart';
import 'package:flutter_riverpod_demo/utils/models/dio_page_result.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

import '../models/policy.dart';
import '../utils/models/dio_result.dart';

part 'policy.g.dart';

@riverpod
Future<List<Policy>> policies(PoliciesRef ref, {int? page}) async {
  var response = await Http.get(ServerUrl.POLICY_PAGE,
      queryParameters: {"current": page ?? 1, "size": 8, "isDeclareMatter": 1});
  final result = response.data as DioPageResult;
  if (result.code != 200) {
    return [];
  }
  List<Policy> products =
      result.data.records.map((item) => Policy.fromJson(item)).toList();
  return products;
}

@riverpod
Future<List<Dictionary>> policyDictionary(
    PolicyDictionaryRef ref, String type) async {
  var response = await Http.get(ServerUrl.POLICY_DICTIONARY,
      queryParameters: {"type": type});
  final result = response.data as DioResult;
  if (result.code != 200) {
    return [];
  }
  List<Dictionary> dictionaries =
      result.data.map((item) => Dictionary.fromJson(item)).toList();
  return dictionaries;
}

@riverpod
Future<DioResult> proposalCreate(
    ProposalCreateRef ref, Map<String, dynamic> data) async {
  var response = await Http.post(ServerUrl.PROPOSAL_CREATE, data: data);
  final result = response.data as DioResult;
  return result;
}

@riverpod
Future<DioResult> captcha(CaptchaRef ref) async {
  var response = await Http.get(ServerUrl.AUTH_CAPTCHA);
  final result = response.data as DioResult;
  return result;
}

@riverpod
Future<DioResult> login(LoginRef ref, Map<String, dynamic> accountParams,
    Map<String, dynamic> captchaData) async {
  var response = await Http.post(ServerUrl.AUTH_TOKEN,
      queryParameters: accountParams, options: Options(headers: captchaData));
  final result = response.data as DioResult;
  return result;
}
